<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Db;

class OrderProduct extends Base
{
    protected $name = 'order_product';


    public static function add($products, $order_id, $uid)
    {
        try {
            $orders = [];
            foreach ($products as $k => $v) {
                if($v['shoptype'] == 'integral' || $v['shoptype'] == 'coupon'){
                    $productinfo = new Lntegral();
                }else{
                    $productinfo = new Product();
                }
                $product=$productinfo->where('id', $v['id'])->field('stock,icon')->find();
                // print('<pre>');print_r($products);die;
                if ($product['stock'] < $v['num']) {
                    return ['code' => -1, 'msg' => "《" . $v['title'] . "》库存不足！"];
                }
                if($v['seckill_id'] !=0){
                    $seckill_stock = SeckillProduct::where(['product_id'=>$v['id'],'seckill_id'=>$v['seckill_id']])->value('stock');
                    if($seckill_stock < $v['num']){
                        return ['code' => -1, 'msg' => "《" . $v['title'] . "》秒杀商品！库存不足！"];
                    }
                }
                $orders[$k]['order_id'] = $order_id;
                $orders[$k]['pid'] = $v['id'];
                $orders[$k]['uid'] = $uid;
                $orders[$k]['shoptype'] = $v['shoptype'];
                $orders[$k]['seckill_id'] = $v['seckill_id'];
                $orders[$k]['product_title'] = $v['title'];
                $orders[$k]['num'] = $v['num'];
                $orders[$k]['spec'] = $v['spec'];
                $orders[$k]['sku_name'] = self::getSpecItemName($v['spec'],$v['shoptype']);
                $orders[$k]['product_image'] = $v['icon'];
                $orders[$k]['price'] = $v['price'];
                $orders[$k]['create_time'] = time();
            }
            if (!empty($orders)) {
                Db::name('order_product')->insertAll($orders);
            }

            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    public static function getSpecItemName($str,$shoptype)
    {
        $spec_item = explode('-', $str);
        $arr = [];
        foreach ($spec_item as $v) {
            if($shoptype == 'lntegral'|| $shoptype == 'coupon'){
                $name= LntegralSpecItem::where('id', $v)->value('name');
            }else{
                $name= SpecItem::where('id', $v)->value('name');
            }
            $arr[] = $name;
        }
        return implode('-', $arr);
    }

    public function getProductImageAttr($value)
    {
        return handleImg($value);
    }
}
